package com.vegetable.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.util.*;

/**
 * 实体差异比较工具类
 */
@Slf4j
public class EntityDiffUtils {
    
    private static final ObjectMapper objectMapper = new ObjectMapper();
    
    /**
     * 获取ObjectMapper实例
     * @return ObjectMapper实例
     */
    public static ObjectMapper getObjectMapper() {
        return objectMapper;
    }
    
    /**
     * 比较两个对象的差异
     * @param oldObj 修改前的对象
     * @param newObj 修改后的对象
     * @return 差异的Map，key为属性名，value为[oldValue, newValue]数组
     */
    public static Map<String, Object[]> compareObjects(Object oldObj, Object newObj) {
        if (oldObj == null && newObj == null) {
            return Collections.emptyMap();
        }
        
        if (oldObj == null || newObj == null) {
            try {
                Map<String, Object[]> result = new HashMap<>();
                result.put("fullObject", new Object[]{
                    oldObj == null ? null : objectMapper.writeValueAsString(oldObj),
                    newObj == null ? null : objectMapper.writeValueAsString(newObj)
                });
                return result;
            } catch (JsonProcessingException e) {
                log.error("序列化对象时出错", e);
                return Collections.emptyMap();
            }
        }
        
        if (!oldObj.getClass().equals(newObj.getClass())) {
            throw new IllegalArgumentException("两个对象必须是相同类型");
        }
        
        Map<String, Object[]> differences = new HashMap<>();
        BeanWrapper oldWrapper = new BeanWrapperImpl(oldObj);
        BeanWrapper newWrapper = new BeanWrapperImpl(newObj);
        
        PropertyDescriptor[] propertyDescriptors = oldWrapper.getPropertyDescriptors();
        
        for (PropertyDescriptor pd : propertyDescriptors) {
            String propertyName = pd.getName();
            if ("class".equals(propertyName)) {
                continue;
            }
            
            Object oldValue = oldWrapper.getPropertyValue(propertyName);
            Object newValue = newWrapper.getPropertyValue(propertyName);
            
            if (!Objects.equals(oldValue, newValue)) {
                differences.put(propertyName, new Object[]{oldValue, newValue});
            }
        }
        
        return differences;
    }
    
    /**
     * 比较两个对象的差异，包含字段中文描述和嵌套对象展开
     * @param oldObj 修改前的对象
     * @param newObj 修改后的对象
     * @return 差异详情列表，包含字段名、中文描述、旧值、新值
     */
    public static List<Map<String, Object>> compareObjectsWithDescriptions(Object oldObj, Object newObj) {
        log.debug("compareObjectsWithDescriptions called with oldObj: {}, newObj: {}", oldObj, newObj);
        
        List<Map<String, Object>> result = new ArrayList<>();
        
        if (oldObj == null && newObj == null) {
            log.debug("Both objects are null, returning empty list");
            return result;
        }
        
        // 当其中一个对象为null时，我们需要逐个字段进行比较
        if (oldObj == null || newObj == null) {
            log.debug("One object is null, processing individual fields");
            // 如果其中一个对象为null，另一个不为null，则所有字段都发生了变更
            Object nonNullObj = (oldObj != null) ? oldObj : newObj;
            processNullObjectFields(nonNullObj, oldObj, newObj, result);
            return result;
        }
        
        if (!oldObj.getClass().equals(newObj.getClass())) {
            log.error("两个对象必须是相同类型: oldObj class: {}, newObj class: {}", oldObj.getClass(), newObj.getClass());
            throw new IllegalArgumentException("两个对象必须是相同类型");
        }
        
        try {
            log.debug("开始递归比较对象");
            compareObjectsRecursive("", "", oldObj, newObj, result);
            log.debug("递归比较完成，结果数量: {}", result.size());
        } catch (Exception e) {
            log.error("比较对象时出错", e);
        }
        
        return result;
    }
    
    /**
     * 处理其中一个对象为null的情况，逐个字段进行比较
     * @param nonNullObj 非null的对象
     * @param oldObj 旧对象
     * @param newObj 新对象
     * @param result 结果列表
     */
    private static void processNullObjectFields(Object nonNullObj, Object oldObj, Object newObj, List<Map<String, Object>> result) {
        log.debug("Processing null object fields for object: {}", nonNullObj);
        
        // 添加递归结束条件，避免对非系统自定义类进行递归
        if (!isComplexType(nonNullObj.getClass())) {
            log.debug("Object is not complex type, adding to result directly");
            Map<String, Object> item = new HashMap<>();
            item.put("fieldName", "fullObject");
            item.put("fieldDescription", "完整对象");
            item.put("oldValue", oldObj);
            item.put("newValue", newObj);
            result.add(item);
            return;
        }
        
        // 特殊处理集合类型
        if (isCollectionType(nonNullObj.getClass())) {
            log.debug("Object is collection type, processing with compareCollectionObjects");
            compareCollectionObjects("", "集合", oldObj, newObj, result);
            return;
        }
        
        try {
            BeanWrapper wrapper = new BeanWrapperImpl(nonNullObj);
            PropertyDescriptor[] propertyDescriptors = wrapper.getPropertyDescriptors();
            
            for (PropertyDescriptor pd : propertyDescriptors) {
                String propertyName = pd.getName();
                if ("class".equals(propertyName)) {
                    continue;
                }
                
                Object value = wrapper.getPropertyValue(propertyName);
                
                // 获取字段的中文描述
                String fieldDescription = getFieldDescription(nonNullObj.getClass(), propertyName);
                if (fieldDescription == null) {
                    fieldDescription = propertyName;
                }
                
                // 特殊处理集合类型
                if (value != null && isCollectionType(value.getClass())) {
                    log.debug("Property {} is collection type, processing with compareCollectionObjects", propertyName);
                    compareCollectionObjects(propertyName, fieldDescription, (oldObj == null) ? null : value, (newObj == null) ? null : value, result);
                }
                // 添加递归结束条件，只对复杂类型进行递归
                else if (value != null && isComplexType(value.getClass())) {
                    log.debug("Property {} is complex object, recursing", propertyName);
                    // 对于复杂对象，递归处理
                    compareObjectsRecursive(propertyName, fieldDescription, (oldObj == null) ? null : value, (newObj == null) ? null : value, result);
                } else {
                    Map<String, Object> item = new HashMap<>();
                    item.put("fieldName", propertyName);
                    item.put("fieldDescription", fieldDescription);
                    // 根据哪个对象为null来设置oldValue和newValue
                    item.put("oldValue", (oldObj == null) ? null : value);
                    item.put("newValue", (newObj == null) ? null : value);
                    result.add(item);
                }
            }
        } catch (Exception e) {
            log.error("处理null对象字段时出错", e);
            // 即使处理出错，也要确保每个字段都被处理
            try {
                // 尝试使用反射直接获取字段
                Field[] fields = nonNullObj.getClass().getDeclaredFields();
                for (Field field : fields) {
                    field.setAccessible(true);
                    String fieldName = field.getName();
                    if ("class".equals(fieldName)) {
                        continue;
                    }
                    
                    Object value = field.get(nonNullObj);
                    
                    // 获取字段的中文描述
                    String fieldDescription = getFieldDescription(nonNullObj.getClass(), fieldName);
                    if (fieldDescription == null) {
                        fieldDescription = fieldName;
                    }
                    
                    // 特殊处理集合类型
                    if (value != null && isCollectionType(value.getClass())) {
                        log.debug("Field {} is collection type, processing with compareCollectionObjects", fieldName);
                        compareCollectionObjects(fieldName, fieldDescription, (oldObj == null) ? null : value, (newObj == null) ? null : value, result);
                    }
                    // 添加递归结束条件，只对复杂类型进行递归
                    else if (value != null && isComplexType(value.getClass())) {
                        log.debug("Field {} is complex object, recursing", fieldName);
                        // 对于复杂对象，递归处理
                        compareObjectsRecursive(fieldName, fieldDescription, (oldObj == null) ? null : value, (newObj == null) ? null : value, result);
                    } else {
                        Map<String, Object> item = new HashMap<>();
                        item.put("fieldName", fieldName);
                        item.put("fieldDescription", fieldDescription);
                        // 根据哪个对象为null来设置oldValue和newValue
                        item.put("oldValue", (oldObj == null) ? null : value);
                        item.put("newValue", (newObj == null) ? null : value);
                        result.add(item);
                    }
                }
            } catch (Exception ex) {
                log.error("使用反射处理null对象字段时也出错", ex);
                // 如果所有方法都失败，回退到原来的逻辑
                Map<String, Object> item = new HashMap<>();
                item.put("fieldName", "fullObject");
                item.put("fieldDescription", "完整对象");
                item.put("oldValue", oldObj);
                item.put("newValue", newObj);
                result.add(item);
            }
        }
    }
    
    /**
     * 递归比较对象属性
     * @param prefix 属性前缀
     * @param prefixDescription 前缀描述
     * @param oldObj 旧对象
     * @param newObj 新对象
     * @param result 结果列表
     */
    private static void compareObjectsRecursive(String prefix, String prefixDescription, Object oldObj, Object newObj, List<Map<String, Object>> result) {
        log.debug("compareObjectsRecursive called with prefix: {}, oldObj: {}, newObj: {}", prefix, oldObj, newObj);
        
        if (oldObj == null && newObj == null) {
            log.debug("Both objects are null, returning");
            return;
        }
        
        // 当其中一个对象为null时，我们需要逐个字段进行比较
        if (oldObj == null || newObj == null) {
            log.debug("One object is null in recursive comparison, processing individual fields");
            processNullObjectInRecursion(prefix, prefixDescription, oldObj, newObj, result);
            return;
        }
        
        if (!oldObj.getClass().equals(newObj.getClass())) {
            log.debug("Objects have different classes, adding to result");
            Map<String, Object> item = new HashMap<>();
            item.put("fieldName", prefix);
            item.put("fieldDescription", prefixDescription);
            item.put("oldValue", oldObj);
            item.put("newValue", newObj);
            result.add(item);
            return;
        }
        
        // 特殊处理集合类型 - 检查当前对象是否为集合类型
        if (isCollectionType(oldObj.getClass())) {
            log.debug("Processing collection type at object level");
            compareCollectionObjects(prefix, prefixDescription, oldObj, newObj, result);
            return;
        }
        
        BeanWrapper oldWrapper = new BeanWrapperImpl(oldObj);
        BeanWrapper newWrapper = new BeanWrapperImpl(newObj);
        
        PropertyDescriptor[] propertyDescriptors = oldWrapper.getPropertyDescriptors();
        
        for (PropertyDescriptor pd : propertyDescriptors) {
            String propertyName = pd.getName();
            if ("class".equals(propertyName)) {
                continue;
            }
            
            Object oldValue = oldWrapper.getPropertyValue(propertyName);
            Object newValue = newWrapper.getPropertyValue(propertyName);
            
            // 获取字段的中文描述
            String fieldDescription = getFieldDescription(oldObj.getClass(), propertyName);
            if (fieldDescription == null) {
                fieldDescription = propertyName;
            }
            
            String fullPropertyName = prefix.isEmpty() ? propertyName : prefix + "." + propertyName;
            String fullDescription = prefixDescription.isEmpty() ? fieldDescription : prefixDescription + " - " + fieldDescription;
            
            log.debug("Processing property: {}, oldValue: {}, newValue: {}", propertyName, oldValue, newValue);
            
            // 特殊处理集合类型 - 检查属性值是否为集合类型
            if ((oldValue != null && isCollectionType(oldValue.getClass())) || 
                (newValue != null && isCollectionType(newValue.getClass()))) {
                log.debug("Property {} is collection type, processing with compareCollectionObjects", propertyName);
                if (isCollectionType(oldValue != null ? oldValue.getClass() : newValue.getClass())) {
                    compareCollectionObjects(fullPropertyName, fullDescription, oldValue, newValue, result);
                } else {
                    // 如果只有一方是集合类型，直接比较
                    if (!Objects.equals(oldValue, newValue)) {
                        Map<String, Object> item = new HashMap<>();
                        item.put("fieldName", fullPropertyName);
                        item.put("fieldDescription", fullDescription);
                        item.put("oldValue", oldValue);
                        item.put("newValue", newValue);
                        result.add(item);
                    }
                }
            }
            // 如果是复杂对象且不为null，递归处理
            else if (isComplexObject(oldValue, newValue) && (oldValue != null || newValue != null)) {
                log.debug("Property {} is complex object, recursing", propertyName);
                compareObjectsRecursive(fullPropertyName, fullDescription, oldValue, newValue, result);
            } else if (!Objects.equals(oldValue, newValue)) {
                // 基本类型或简单对象的差异
                log.debug("Property {} has changed, adding to result", propertyName);
                Map<String, Object> item = new HashMap<>();
                item.put("fieldName", fullPropertyName);
                item.put("fieldDescription", fullDescription);
                item.put("oldValue", oldValue);
                item.put("newValue", newValue);
                result.add(item);
            }
        }
    }
    
    /**
     * 在递归比较中处理其中一个对象为null的情况
     * @param prefix 属性前缀
     * @param prefixDescription 前缀描述
     * @param oldObj 旧对象
     * @param newObj 新对象
     * @param result 结果列表
     */
    private static void processNullObjectInRecursion(String prefix, String prefixDescription, Object oldObj, Object newObj, List<Map<String, Object>> result) {
        log.debug("Processing null object in recursion with prefix: {}", prefix);
        
        // 确定非null的对象
        Object nonNullObj = (oldObj != null) ? oldObj : newObj;
        
        // 添加递归结束条件，避免对非系统自定义类进行递归
        if (nonNullObj != null && !isComplexType(nonNullObj.getClass())) {
            log.debug("Object is not complex type, adding to result directly");
            Map<String, Object> item = new HashMap<>();
            item.put("fieldName", prefix);
            item.put("fieldDescription", prefixDescription);
            item.put("oldValue", oldObj);
            item.put("newValue", newObj);
            result.add(item);
            return;
        }
        
        // 特殊处理集合类型
        if (nonNullObj != null && isCollectionType(nonNullObj.getClass())) {
            log.debug("Object is collection type, processing with compareCollectionObjects");
            compareCollectionObjects(prefix, prefixDescription, oldObj, newObj, result);
            return;
        }
        
        try {
            BeanWrapper wrapper = new BeanWrapperImpl(nonNullObj);
            PropertyDescriptor[] propertyDescriptors = wrapper.getPropertyDescriptors();
            
            for (PropertyDescriptor pd : propertyDescriptors) {
                String propertyName = pd.getName();
                if ("class".equals(propertyName)) {
                    continue;
                }
                
                Object value = wrapper.getPropertyValue(propertyName);
                
                // 获取字段的中文描述
                String fieldDescription = getFieldDescription(nonNullObj.getClass(), propertyName);
                if (fieldDescription == null) {
                    fieldDescription = propertyName;
                }
                
                String fullPropertyName = prefix.isEmpty() ? propertyName : prefix + "." + propertyName;
                String fullDescription = prefixDescription.isEmpty() ? fieldDescription : prefixDescription + " - " + fieldDescription;
                
                // 特殊处理集合类型
                if (value != null && isCollectionType(value.getClass())) {
                    log.debug("Property {} is collection type, processing with compareCollectionObjects", propertyName);
                    compareCollectionObjects(fullPropertyName, fullDescription, (oldObj == null) ? null : value, (newObj == null) ? null : value, result);
                }
                // 添加递归结束条件，只对复杂类型进行递归
                else if (value != null && isComplexType(value.getClass())) {
                    log.debug("Property {} is complex object, recursing", propertyName);
                    // 对于复杂对象，递归处理
                    compareObjectsRecursive(fullPropertyName, fullDescription, (oldObj == null) ? null : value, (newObj == null) ? null : value, result);
                } else {
                    Map<String, Object> item = new HashMap<>();
                    item.put("fieldName", fullPropertyName);
                    item.put("fieldDescription", fullDescription);
                    // 根据哪个对象为null来设置oldValue和newValue
                    item.put("oldValue", (oldObj == null) ? null : value);
                    item.put("newValue", (newObj == null) ? null : value);
                    result.add(item);
                }
            }
        } catch (Exception e) {
            log.error("处理递归中的null对象时出错", e);
            // 即使处理出错，也要确保每个字段都被处理
            try {
                // 尝试使用反射直接获取字段
                Field[] fields = nonNullObj.getClass().getDeclaredFields();
                for (Field field : fields) {
                    field.setAccessible(true);
                    String fieldName = field.getName();
                    if ("class".equals(fieldName)) {
                        continue;
                    }
                    
                    Object value = field.get(nonNullObj);
                    
                    // 获取字段的中文描述
                    String fieldDescription = getFieldDescription(nonNullObj.getClass(), fieldName);
                    if (fieldDescription == null) {
                        fieldDescription = fieldName;
                    }
                    
                    String fullPropertyName = prefix.isEmpty() ? fieldName : prefix + "." + fieldName;
                    String fullDescription = prefixDescription.isEmpty() ? fieldDescription : prefixDescription + " - " + fieldDescription;
                    
                    // 特殊处理集合类型
                    if (value != null && isCollectionType(value.getClass())) {
                        log.debug("Field {} is collection type, processing with compareCollectionObjects", fieldName);
                        compareCollectionObjects(fullPropertyName, fullDescription, (oldObj == null) ? null : value, (newObj == null) ? null : value, result);
                    }
                    // 添加递归结束条件，只对复杂类型进行递归
                    else if (value != null && isComplexType(value.getClass())) {
                        log.debug("Field {} is complex object, recursing", fieldName);
                        // 对于复杂对象，递归处理
                        compareObjectsRecursive(fullPropertyName, fullDescription, (oldObj == null) ? null : value, (newObj == null) ? null : value, result);
                    } else {
                        Map<String, Object> item = new HashMap<>();
                        item.put("fieldName", fullPropertyName);
                        item.put("fieldDescription", fullDescription);
                        // 根据哪个对象为null来设置oldValue和newValue
                        item.put("oldValue", (oldObj == null) ? null : value);
                        item.put("newValue", (newObj == null) ? null : value);
                        result.add(item);
                    }
                }
            } catch (Exception ex) {
                log.error("使用反射处理递归中的null对象时也出错", ex);
                // 如果所有方法都失败，回退到原来的逻辑
                Map<String, Object> item = new HashMap<>();
                item.put("fieldName", prefix);
                item.put("fieldDescription", prefixDescription);
                item.put("oldValue", oldObj);
                item.put("newValue", newObj);
                result.add(item);
            }
        }
    }
    
    /**
     * 比较集合对象中的元素
     * @param prefix 属性前缀
     * @param prefixDescription 前缀描述
     * @param oldCollection 旧集合
     * @param newCollection 新集合
     * @param result 结果列表
     */
    private static void compareCollectionObjects(String prefix, String prefixDescription, Object oldCollection, Object newCollection, List<Map<String, Object>> result) {
        log.debug("compareCollectionObjects called with prefix: {}, oldCollection: {}, newCollection: {}", prefix, oldCollection, newCollection);
        
        // 处理null值情况
        if (oldCollection == null && newCollection == null) {
            log.debug("Both collections are null, nothing to compare");
            return;
        }
        
        // 即使其中一个为null，也要检查另一个是否是集合类型，因为需要展示每个属性的名称
        boolean oldIsCollection = (oldCollection instanceof Collection);
        boolean newIsCollection = (newCollection instanceof Collection);
        
        // 只要确定其中一个为集合类型即可，因为同一个属性如果之前是集合，修改后也应该是集合
        if (!oldIsCollection && !newIsCollection) {
            log.debug("Neither object is a collection, adding to result");
            Map<String, Object> item = new HashMap<>();
            item.put("fieldName", prefix);
            item.put("fieldDescription", prefixDescription);
            item.put("oldValue", oldCollection);
            item.put("newValue", newCollection);
            result.add(item);
            return;
        }
        
        // 获取集合引用
        Collection<?> oldColl = oldIsCollection ? (Collection<?>) oldCollection : null;
        Collection<?> newColl = newIsCollection ? (Collection<?>) newCollection : null;
        
        log.debug("Old collection size: {}, New collection size: {}", 
                  oldColl != null ? oldColl.size() : "N/A", 
                  newColl != null ? newColl.size() : "N/A");
        
        // 处理其中一个为null的情况（常见于新增或删除操作）
        if (oldColl == null || newColl == null) {
            log.debug("One collection is null, processing individual elements");
            // 展开非null集合中的元素
            Collection<?> nonNullColl = (oldColl != null) ? oldColl : newColl;
            boolean isOldNull = (oldColl == null);
            
            int index = 0;
            for (Object element : nonNullColl) {
                String elementPrefix = prefix + "[" + index + "]";
                String elementDescription = prefixDescription + " - 元素[" + index + "]";
                
                log.debug("Processing element at index {}: {}", index, element);
                
                // 添加递归结束条件，只对复杂类型进行递归
                if (element != null && isComplexType(element.getClass())) {
                    log.debug("Element is complex object, recursing");
                    compareObjectsRecursive(elementPrefix, elementDescription, 
                                          isOldNull ? null : element, 
                                          isOldNull ? element : null, 
                                          result);
                } else {
                    // 为每个属性设置正确的fieldDescription
                    addElementToResult(elementPrefix, elementDescription, 
                                     isOldNull ? null : element, 
                                     isOldNull ? element : null, 
                                     result);
                }
                index++;
            }
            return;
        }
        
        // 展开集合中的元素进行比较
        int index = 0;
        Iterator<?> oldIter = oldColl.iterator();
        Iterator<?> newIter = newColl.iterator();
        
        // 比较共同索引的元素
        while (oldIter.hasNext() && newIter.hasNext()) {
            Object oldElement = oldIter.next();
            Object newElement = newIter.next();
            
            String elementPrefix = prefix + "[" + index + "]";
            String elementDescription = prefixDescription + " - 元素[" + index + "]";
            
            log.debug("Comparing collection element at index {}: oldElement: {}, newElement: {}", index, oldElement, newElement);
            
            // 添加递归结束条件，只对复杂类型进行递归
            if (oldElement != null && newElement != null && 
                oldElement.getClass().equals(newElement.getClass()) &&
                isComplexType(oldElement.getClass())) {
                log.debug("Both elements are complex objects, recursing");
                compareObjectsRecursive(elementPrefix, elementDescription, oldElement, newElement, result);
            } else if (!Objects.equals(oldElement, newElement)) {
                log.debug("Elements are different, adding to result");
                // 为每个属性设置正确的fieldDescription
                addElementToResult(elementPrefix, elementDescription, oldElement, newElement, result);
            }
            index++;
        }
        
        // 处理剩余的元素（旧集合中多余的元素）
        while (oldIter.hasNext()) {
            Object oldElement = oldIter.next();
            String elementPrefix = prefix + "[" + index + "]";
            String elementDescription = prefixDescription + " - 元素[" + index + "]";
            
            log.debug("Handling remaining old element at index {}: {}", index, oldElement);
            
            // 添加递归结束条件，只对复杂类型进行递归
            if (oldElement != null && isComplexType(oldElement.getClass())) {
                log.debug("Old element is complex object, recursing with null new element");
                // 对于删除的复杂对象，我们需要展开其属性
                compareObjectsRecursive(elementPrefix, elementDescription, oldElement, null, result);
            } else {
                // 为每个属性设置正确的fieldDescription
                addElementToResult(elementPrefix, elementDescription, oldElement, null, result);
            }
            index++;
        }
        
        // 处理剩余的元素（新集合中多余的元素）
        while (newIter.hasNext()) {
            Object newElement = newIter.next();
            String elementPrefix = prefix + "[" + index + "]";
            String elementDescription = prefixDescription + " - 元素[" + index + "]";
            
            log.debug("Handling remaining new element at index {}: {}", index, newElement);
            
            // 添加递归结束条件，只对复杂类型进行递归
            if (newElement != null && isComplexType(newElement.getClass())) {
                log.debug("New element is complex object, recursing with null old element");
                // 对于新增的复杂对象，我们需要展开其属性
                compareObjectsRecursive(elementPrefix, elementDescription, null, newElement, result);
            } else {
                // 为每个属性设置正确的fieldDescription
                addElementToResult(elementPrefix, elementDescription, null, newElement, result);
            }
            index++;
        }
    }
    
    /**
     * 将元素添加到结果列表中，为每个属性设置正确的描述
     * @param elementPrefix 元素前缀
     * @param elementDescription 元素描述
     * @param oldElement 旧元素
     * @param newElement 新元素
     * @param result 结果列表
     */
    private static void addElementToResult(String elementPrefix, String elementDescription, Object oldElement, Object newElement, List<Map<String, Object>> result) {
        // 如果元素是Map类型，展开Map中的每个键值对
        if ((oldElement instanceof Map) || (newElement instanceof Map)) {
            Map<String, Object> oldMap = (oldElement instanceof Map) ? (Map<String, Object>) oldElement : Collections.emptyMap();
            Map<String, Object> newMap = (newElement instanceof Map) ? (Map<String, Object>) newElement : Collections.emptyMap();
            
            // 处理所有键
            Set<String> allKeys = new HashSet<>();
            allKeys.addAll(oldMap.keySet());
            allKeys.addAll(newMap.keySet());
            
            for (String key : allKeys) {
                Object oldValue = oldMap.get(key);
                Object newValue = newMap.get(key);
                
                if (!Objects.equals(oldValue, newValue)) {
                    Map<String, Object> item = new HashMap<>();
                    item.put("fieldName", elementPrefix + "." + key);
                    item.put("fieldDescription", elementDescription + " - " + key);
                    item.put("oldValue", oldValue);
                    item.put("newValue", newValue);
                    result.add(item);
                }
            }
        } else {
            // 对于非Map类型的元素，直接添加
            Map<String, Object> item = new HashMap<>();
            item.put("fieldName", elementPrefix);
            item.put("fieldDescription", elementDescription);
            item.put("oldValue", oldElement);
            item.put("newValue", newElement);
            result.add(item);
        }
    }
    
    /**
     * 判断是否为复杂对象（需要递归处理）
     * @param oldValue 旧值
     * @param newValue 新值
     * @return 是否为复杂对象
     */
    private static boolean isComplexObject(Object oldValue, Object newValue) {
        // 如果任一值为null，检查另一个值是否为复杂类型
        if (oldValue == null && newValue != null) {
            return isComplexType(newValue.getClass());
        }
        if (newValue == null && oldValue != null) {
            return isComplexType(oldValue.getClass());
        }
        
        // 如果两个值都不为null，检查是否为复杂类型
        if (oldValue != null && newValue != null) {
            Class<?> clazz = oldValue.getClass();
            // 对于集合类型，我们仍然认为是复杂对象，需要特殊处理
            if (isCollectionType(clazz)) {
                return true;
            }
            return isComplexType(clazz);
        }
        
        return false;
    }
    
    /**
     * 判断是否为复杂类型
     * @param clazz 类型
     * @return 是否为复杂类型
     */
    private static boolean isComplexType(Class<?> clazz) {
        // 基本类型和包装类型不是复杂类型
        if (clazz.isPrimitive() || isWrapperType(clazz) || clazz == String.class || 
            clazz == Date.class || clazz.isEnum()) {
            return false;
        }
        
        // 集合类型需要特殊处理，但在这里我们仍然认为它们是复杂类型
        if (isCollectionType(clazz)) {
            return true;
        }
        
        // 只对系统自定义的类进行递归处理，避免对第三方库类进行递归
        String className = clazz.getName();
        if (className.startsWith("java.") || className.startsWith("javax.") || 
            className.startsWith("com.sun.") || className.startsWith("sun.")) {
            return false;
        }
        
        // 其他类型认为是复杂类型，需要递归处理
        return true;
    }
    
    /**
     * 判断是否为集合类型
     * @param clazz 类型
     * @return 是否为集合类型
     */
    private static boolean isCollectionType(Class<?> clazz) {
        return Collection.class.isAssignableFrom(clazz) || clazz.isArray();
    }
    
    /**
     * 判断是否为包装类型
     * @param clazz 类型
     * @return 是否为包装类型
     */
    private static boolean isWrapperType(Class<?> clazz) {
        return clazz == Boolean.class || clazz == Character.class ||
               clazz == Byte.class || clazz == Short.class ||
               clazz == Integer.class || clazz == Long.class ||
               clazz == Float.class || clazz == Double.class;
    }
    
    /**
     * 获取字段的中文描述（从ApiModelProperty注解中获取）
     * @param clazz 类
     * @param fieldName 字段名
     * @return 字段中文描述
     */
    private static String getFieldDescription(Class<?> clazz, String fieldName) {
        try {
            Field field = getField(clazz, fieldName);
            if (field != null) {
                ApiModelProperty annotation = field.getAnnotation(ApiModelProperty.class);
                if (annotation != null && !annotation.value().isEmpty()) {
                    return annotation.value();
                }
            }
        } catch (Exception e) {
            log.debug("获取字段描述时出错: {}", fieldName, e);
        }
        return fieldName;
    }
    
    /**
     * 获取字段（包括父类中的字段）
     * @param clazz 类
     * @param fieldName 字段名
     * @return 字段
     */
    private static Field getField(Class<?> clazz, String fieldName) {
        while (clazz != null) {
            try {
                return clazz.getDeclaredField(fieldName);
            } catch (NoSuchFieldException e) {
                clazz = clazz.getSuperclass();
            }
        }
        return null;
    }
    
    /**
     * 将对象转换为JSON字符串
     * @param obj 对象
     * @return JSON字符串
     */
    public static String toJson(Object obj) {
        if (obj == null) {
            return null;
        }
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            log.error("序列化对象时出错", e);
            return obj.toString();
        }
    }
    
    /**
     * 将JSON字符串转换为Map
     * @param json JSON字符串
     * @return Map对象
     */
    public static Map<String, Object> fromJsonToMap(String json) {
        if (json == null || json.isEmpty()) {
            return Collections.emptyMap();
        }
        try {
            return objectMapper.readValue(json, Map.class);
        } catch (JsonProcessingException e) {
            log.error("反序列化JSON时出错", e);
            return Collections.emptyMap();
        }
    }
    
    /**
     * 生成字段变更详情的友好描述
     * @param beforeData 修改前的数据
     * @param afterData 修改后的数据
     * @return 字段变更详情
     */
    public static Map<String, Object[]> generateFieldChanges(String beforeData, String afterData) {
        if (beforeData == null && afterData == null) {
            return Collections.emptyMap();
        }
        
        try {
            Map<String, Object> beforeMap = beforeData != null ? fromJsonToMap(beforeData) : Collections.emptyMap();
            Map<String, Object> afterMap = afterData != null ? fromJsonToMap(afterData) : Collections.emptyMap();
            
            Map<String, Object[]> changes = new HashMap<>();
            
            // 处理修改后的字段
            for (Map.Entry<String, Object> entry : afterMap.entrySet()) {
                String key = entry.getKey();
                Object newValue = entry.getValue();
                Object oldValue = beforeMap.get(key);
                
                if (!Objects.equals(oldValue, newValue)) {
                    changes.put(key, new Object[]{oldValue, newValue});
                }
            }
            
            // 处理删除的字段
            for (Map.Entry<String, Object> entry : beforeMap.entrySet()) {
                String key = entry.getKey();
                if (!afterMap.containsKey(key)) {
                    changes.put(key, new Object[]{entry.getValue(), null});
                }
            }
            
            return changes;
        } catch (Exception e) {
            log.error("生成字段变更详情时出错", e);
            return Collections.emptyMap();
        }
    }
}